//
//  MyAccountViewController.m
//  RedManStock
//
//  Created by lanou3g on 15/8/1.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "MyAccountViewController.h"
#import "ParameterHeader.h"
#import "PositionTableViewCell.h"
#import "MyCoreHandle.h"
#import "MyCorePosition.h"
#import "MyCoreEntrust.h"
#import "SimpleStock.h"
@interface MyAccountViewController ()
@property (nonatomic,retain) NSArray *positionArray;
@end

@implementation MyAccountViewController

static int requestTime=0;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //头表
    NSArray *nibArray=[[NSBundle mainBundle] loadNibNamed:@"MyAccountHeadView" owner:self options:nil];
    self.myAccountHeadView=nibArray[0];
    
    self.tableView.tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 200)];
    self.myAccountHeadView.frame=CGRectMake(0, 0, self.view.bounds.size.width, 200);
    self.myAccountHeadView.backgroundColor=MyRedColor;
    [self.tableView.tableHeaderView addSubview:self.myAccountHeadView];
    
    //得加个footerView，让信息从tabBar下面出来
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 49)];
    self.tableView.tableFooterView=view;
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"PositionTableViewCell" bundle:nil] forCellReuseIdentifier:@"PositionTableViewCell"];
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    //这一步中，既实现了数据请求，又
    [self loadNewData];
}

- (void)loadNewData{
    
    //读取数据库中的Position信息,没有初始化，可能为空
    self.positionArray=[[MyCoreHandle shareHandle] selectAllCorePosition];
    if (self.positionArray.count==0) {
        //负责headView上的用户信息及数据库
        [self resetUserInfo];
        [self.tableView.header endRefreshing];
        return;
    }
    
    //必须通过requestTime，当它++最后等于self.positionArray.count的时候，才做下一步操作
    requestTime=0;
    
    //负责下方cell的视图
    NSString *url=@"http://api.gongniucaijing.com/stock/info";
    for (MyCorePosition *myPosition in self.positionArray) {
        [[MyHandle new] requestDataWithURLStr:url parameterBlock:^NSDictionary *{
            
            NSDictionary *dic=@{@"code":myPosition.stockCode,
                                @"token":Token};
            return dic;
        } successBlock:^(NSDictionary *responseDic) {
            
            requestTime++;
            NSLog(@"----requestTime=%d",requestTime);
            
            SimpleStock *simpleStock=[[SimpleStock alloc]init];
            simpleStock.name=myPosition.stockName;
            simpleStock.code=myPosition.stockCode;
            simpleStock.volume=@"0";
            simpleStock.entrustPrice=@"0";
            simpleStock.nowPrice=[[[responseDic objectForKey:@"data"] objectForKey:@"nowPrice"] stringValue];
            simpleStock.which=@"冻结资金";//只有给了这个才会走更新数据
            //一个一个先存
            [[MyCoreHandle shareHandle] addMyPosition:simpleStock];
            
            //当全部请求结束后，才开始获得全部数据源，设置用户信息（存/取），更新视图
            if (requestTime==self.positionArray.count) {
                self.positionArray=[[MyCoreHandle shareHandle] selectAllCorePosition];
                
                //负责headView上的用户信息及数据库
                [self resetUserInfo];
                
                //刷新视图
                [self.tableView reloadData];
                //结束刷新
                [self.tableView.header endRefreshing];
            }
            
        } errorBlock:^(NSError *error) {
            [MyHandle setUpMBProgressWithView:self.view Text:@"网络错误，请检查网络"];
        }];
    }
    
    
    
}
#pragma mark 请求好数据之后设置headView，并处理用户的数据
- (void)resetUserInfo{
    
    NSArray *array=[[MyCoreHandle shareHandle] selectAllCorePosition];
    float sum=0;
    for (MyCorePosition *myPosition in array) {
        sum=sum+[myPosition.nowTotalPrice floatValue];
    }
    
    //解档
    User *myUser=[NSKeyedUnarchiver unarchiveObjectWithFile: [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.plist"]];
    
    //现在的股票市值为sum；股票市值增加了多少，相应的总资产就要减去多少，差值是固定的，即a1
    float a1=sum-[myUser.totalPrice floatValue];
    myUser.totalPrice=[NSString stringWithFormat:@"%.2f",sum];
    float a2=[myUser.totalAsset floatValue]+a1;
    myUser.totalAsset=[NSString stringWithFormat:@"%.2f",a2];
    myUser.availableAsset=[NSString stringWithFormat:@"%.2f",[myUser.totalAsset floatValue]-[myUser.totalPrice floatValue]];
    float b=([myUser.totalAsset floatValue]-1000000)/1000000;
    myUser.totalYield=[NSString stringWithFormat:@"%.2f%%",b*100];
    myUser.day_yield=[NSString stringWithFormat:@"%.2f",[myUser.totalAsset floatValue]-[myUser.lastTotalAsset floatValue]];
    float c=[myUser.day_yield floatValue]/[myUser.lastTotalAsset floatValue];
    myUser.day_yieldRate=[NSString stringWithFormat:@"%.2f%%",c*100];
    
    
    //设置视图的内容
    [self.myAccountHeadView layoutUserInfoWithUser:myUser];
    
    //归档
    [NSKeyedArchiver archiveRootObject:myUser toFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.plist"]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.positionArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PositionTableViewCell *cell=[self.tableView dequeueReusableCellWithIdentifier:@"PositionTableViewCell" forIndexPath:indexPath];
    MyCorePosition *position=self.positionArray[indexPath.row];
    cell.position=position;
    
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
